import JsPdf from 'jspdf';
import html2canvas from 'html2canvas';
const A4Width = 592.28;
const A4Height = 841.89;

/**
 * @description 导出PDF文件，暂时支持单页
 * @param {string} resumeName 导出文件名
 */
// 添加分页边距
const PAGE_MARGIN = 10; // 15pt 的页边距

export function toPrintPdf(resumeName?: string) {
  let name = resumeName || '未命名文件';
  const dom: HTMLElement | any = document.querySelector('#visPdf');
  if (dom) {
    // 添加分页控制样式
    dom.style.pageBreakInside = 'avoid';
    dom.style.breakInside = 'avoid-page';
    
    html2canvas(dom, {
      allowTaint: true,
      scale: 2, // 提高分辨率
      useCORS: true,
    }).then((canvas) => {
      let contentWidth = canvas.width;
      let contentHeight = canvas.height;
      // 精确计算每页高度
      const scale = contentWidth / (A4Width - PAGE_MARGIN * 2); // 基于内容宽度计算缩放比例
      let pageHeight = (A4Height - PAGE_MARGIN * 2) * scale; // 基于缩放比例计算canvas高度
      pageHeight = Math.min(pageHeight, contentHeight) * 0.99; // 确保不超过总高度，并留5%安全边距
      
      // 获取所有内容块高度
      const contentBlocks = Array.from(dom.querySelectorAll('*[data-pdf-block]')) as HTMLElement[];
      console.log('Total content blocks:', contentBlocks.length);
      
      const blockHeights = contentBlocks.map((el, index) => {
        const rect = el.getBoundingClientRect();
        const height = rect.height;
        const marginTop = parseFloat(getComputedStyle(el).marginTop);
        const marginBottom = parseFloat(getComputedStyle(el).marginBottom);
        const totalHeight = (height + marginTop + marginBottom) * scale;
        
        console.log(`Block ${index + 1}:`, {
          height,
          marginTop,
          marginBottom,
          totalHeight,
          rect,
          computedStyle: getComputedStyle(el)
        });
        
        return totalHeight;
      });
      
      console.log('Block heights:', blockHeights);
      console.log('Page height:', pageHeight);
      let leftHeight = contentHeight;
      // 页面偏移
      let position = PAGE_MARGIN; // 添加顶部边距
      let imgWidth = A4Width - PAGE_MARGIN * 2; // 减去左右边距
      let imgHeight = (imgWidth / contentWidth) * contentHeight;
      let pageData = canvas.toDataURL('image/jpeg', 1.0);
      // 这里的第一个参数表示方向，这里一定要选择 portrait
      // 具体可看文档 https://artskydj.github.io/jsPDF/docs/jsPDF.html
      let PDF = new JsPdf('portrait', 'pt', 'a4');
      if (leftHeight < pageHeight) {
        PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
      } else {
        while (leftHeight > 0) {
          // 计算当前页面的canvas裁剪区域
          const canvasOffsetY = contentHeight - leftHeight;
          const canvasHeight = Math.min(pageHeight, leftHeight);
          
          // 创建新的canvas绘制当前页内容
          const tempCanvas = document.createElement('canvas');
          const tempCtx = tempCanvas.getContext('2d');
          tempCanvas.width = contentWidth;
          tempCanvas.height = canvasHeight;
          
          if (tempCtx) {
            tempCtx.drawImage(
              canvas,
              0, // 源x
              canvasOffsetY, // 源y
              contentWidth, // 源宽度
              canvasHeight, // 源高度
              0, // 目标x
              0, // 目标y
              contentWidth, // 目标宽度
              canvasHeight // 目标高度
            );
            
            const pageImg = tempCanvas.toDataURL('image/jpeg', 1.0);
            PDF.addImage(pageImg, 'JPEG', PAGE_MARGIN, PAGE_MARGIN, imgWidth, (imgWidth / contentWidth) * canvasHeight);
          }
          
          leftHeight -= pageHeight;
          if (leftHeight > 0) {
            PDF.addPage();
          }
        }
      }
      PDF.save(name + '.pdf');
    });
  }
}
